﻿@using ABC.Controllers.ViewModels
@using ABC.Core.Extentions
@model ABC.Controllers.ViewModels.My.MyAccountViewModel
@{
    ViewBag.Title = "Личные данные - Азбука24";
    Layout = "~/Views/Shared/_MyLayout.cshtml";
}
<div class="row-fluid">
    <!--// Левая колонка -->
    @{Html.RenderPartial("_AccountMenu", new BaseViewModel());}
    <!--// Правая колонка -->
    <script type="text/javascript">
        $(function () {
            $("#avatar_upload").uploadify({
                uploader: '@Url.Action("ChangeAvatar", "Upload")',
                cancelImg: '@Url.VirtualImageUrl("uploadify-cancel.png")',
                swf: '@Url.VirtualScriptUrl("uploadify.swf")',
                formData: { userId: '@Model.CurrentUser.Id' },
                auto: true,
                fileObjName: 'fileUpload',
                hideButton: false,
                fileTypeExts: '*.jpg;*.png;',
                multi: false,
                method: "post",
                fileTypeDesc: 'Файлы изображений *.jpg;*.png;',
                width: '94',
                height: '18',
                buttonText: "Изменить фото",
                onUploadError: function (file, errorCode, errorMsg, errorString) {
                    alert('Файл ' + file.name + ' не был загружен: ' + errorMsg);
                },
                onUploadSuccess: function (file, data, response) {
                    $("#avatar").attr("src", data);
                }

            });
            $(".uploadify").addClass("btn");
            $(".swfupload").css("width", "100px").css("left", "10px");
            $("#avatar_upload-queue").hide();

            $("#birthday").mousedown(rightDate);
            $("#DateLawToCar").mousedown(rightDate);
            function rightDate(obj) {
                if ($(obj.target).val() == "01.01.0001" || $(obj.target).val() == "") {
                    var today = new Date();
                    today.setFullYear(Math.ceil(today.getFullYear() - 18));
                    var todayFormat = ((String(today.getDate()).length == 1) ? "0" + today.getDate() : today.getDate()) + "." + ((String(today.getMonth()).length == 1) ? "0" + Math.ceil(today.getMonth() + 1) : Math.ceil(today.getMonth() + 1)) + "." + ((String(today.getFullYear()).length == 1) ? "0" + today.getFullYear() : today.getFullYear());
                    $(obj.target).val(todayFormat);
                }
            };


            function addField(forLabel, forDiv, nameField, afterIns) {
                var field = "<div class='control-group'><label class='control-label' for='" + nameField + "'>" + forLabel + "</label><div class='controls'>" +
            forDiv + "</div></div>";
                afterIns.after(field);
                $(".phone").mask("+7 (999) 999-99-99");
            };

            function addFieldToForm(eventObject) {
                var f = $("#form1 .control-group");
                switch ($(eventObject.target).text()) {
                    case "Отчество":
                        f.eq(3).removeClass("hide");
                        $(eventObject.target).parent("li").replaceWith("");
                        break;
                    case "Компания":
                        f.eq(5).removeClass("hide");
                        $(eventObject.target).parent("li").replaceWith("");
                        if (f.eq(6).hasClass("hide") && f.eq(7).hasClass("hide")) {
                            f.eq(4).after("<hr>");
                        }
                        break;
                    case "Должность":
                        f.eq(6).removeClass("hide");
                        $(eventObject.target).parent("li").replaceWith("");
                        if (f.eq(5).hasClass("hide") && f.eq(7).hasClass("hide")) {
                            f.eq(4).after("<hr>");
                        }
                        break;
                    case "Отдел":
                        f.eq(7).removeClass("hide");
                        $(eventObject.target).parent("li").replaceWith("");
                        if (f.eq(5).hasClass("hide") && f.eq(6).hasClass("hide")) {
                            f.eq(4).after("<hr>");
                        }
                        break;
                    case "Телефон":
                        var countPhone = $("select[name='PhoneType']").length;
                        var phrase = $("select[name='PhoneType']:last").next("p");
                        $("select[name='PhoneType']:last").next("p").replaceWith("");
                        addField("Телефон", "<input id='PhoneValue" + countPhone + "' class='input-large phone' type='tel' name='PhoneValue" +
                             countPhone + "'/> <select class='input-medium' name='PhoneType'><option value='Мобильный'>Мобильный</option><option value='Рабочий'>Рабочий</option><option value='Домашний'>Домашний</option></select>",
                             "PhoneValue" + countPhone, $("select[name='PhoneType']:last").parents(".control-group"));
                        $("select[name='PhoneType']:last").after(phrase.wrap("<p>"));
                        break;
                    case "Электронная почта":
                        var countEmail = $("select[name='EmailType']").length;
                        console.log(countEmail);
                        addField("Электронная почта", "<input id='EmailValue" + countEmail + "' class='input-large' type='email'name='EmailValue" + countEmail +
                             "' /> <select class='input-medium' name='EmailType'> <option value='Личная'>Личная</option><option value='Рабочая'>Рабочая</option></select>",
                             "EmailValue" + countEmail, $("select[name='EmailType']:last").parents(".control-group"));
                        break;
                    case "IM":
                        var countIm = $("select[name='ImType']").length;
                        addField("IM", "<input id='ImValue" + countIm + "' class='input-large' type='text' name='ImValue" + countIm +
                        "' /> <select class='input-medium' name='ImType'><option value='Icq'>ICQ</option><option value='Jabber'>Jabber</option><option value='Skype'>Skype</option></select>",
                        "ImValue" + countIm, $("select[name='ImType']:last").parents(".control-group"));
                        break;
                    case "Соцсеть":
                        if ($("#SocNetValue0").parents(".control-group").hasClass("hide")) {
                            $("#SocNetValue0").parents(".control-group").removeClass("hide");
                        } else {
                            var countSocNet = $("select[name='SocNetType']").length;
                            addField("Соцсеть", "<input id='SocNetValue" + countSocNet + "' class='input-large' type='text' name='SocNetValue" + countSocNet +
                                "'/> <select class='input-medium' name='SocNetType'><option value='Vkontakte'>Вконтакте</option><option value='Odnoklassniki'>Одноклассники</option><option value='MoyMir'>Мой Мир</option><option value='Facebook'>Facebook</option><option value='MySpace'>MySpace</option></select>",
                                "SocNetValue" + countSocNet, $("select[name='SocNetType']:last").parents(".control-group"));
                        }
                        break;
                    case "Адрес":
                        var countAddress = $("textarea[typefield='address']").length;
                        addField("Адрес", "<textarea id='AddressValue" + countAddress + "' class='input-large' rows='3' typefield='address' placeholder = 'Город, улица, дом ' name='AddressValue" + countAddress +
                        "'></textarea>",
                        "AddressValue" + countAddress, $("textarea[typefield='address']:last").parents(".control-group"));
                        break;
                    case "Дата получения прав":
                        $("#DateLawToCar").parents(".control-group").removeClass("hide");
                        $(eventObject.target).parent("li").replaceWith("");
                        $("#DateLawToCar").val("");
                        break;
                    default: break;
                }
                if ($("#addField ul.dropdown-menu li").eq(0).hasClass("divider")) {
                    $("#addField ul.dropdown-menu li").eq(0).replaceWith("");
                }
                if ($("#addField ul.dropdown-menu li:last").hasClass("divider")) {
                    $("#addField ul.dropdown-menu li:last").replaceWith("");
                }

            }

            $(".span9 ul.dropdown-menu li a").click(addFieldToForm);
            if ($("select[name='PhoneType']").length > 1) {
                for (var i = 0; i < $("select[name='PhoneType']").length - 1; i++) {
                    $("select[name='PhoneType']").eq(i).next("p").replaceWith("");
                }
            }
        });

        function DeleteAvatar() {
            $.ajax({
                url: '@Url.Action("DeleteAvatar", "Upload")',
                type: "POST",
                data: { userId: '@Model.CurrentUser.Id', photoId: '@Model.CurrentUser.Avatar' },
                success: function (data) {
                    $("#avatar").attr("src", data);
                }
            });
        }
        function PostData() {
            $("input[name='countaddress']").val($("textarea[typefield='address']").length);
            $('#form1').submit();
        }
    </script>
    <div class="span9">
        <div class="page-header">
            <h2>
                Личные данные</h2>
        </div>
        <div class="row-fluid">
            <div class="span8">
                @foreach (var phone in Model.ListPhones.Where(phone => !phone.IsActive))
                {
                    <div class="alert alert-info">
                        <p>
                            <strong>Обратите внимание!</strong> Для отправки уведомлений по SMS и просмотра
                            статистики звонков, вам необходимо <a target="_blank" href="@Url.Action("ConfirmPhone", new { phone = phone.Value, index = phone.NameField.Replace("PhoneValue", "") })">
                                подтвердить номер телефона @phone.Value</a>.</p>
                    </div>
                }
                @foreach (var email in Model.ListEmails.Where(email => !email.IsActive))
                {
                    <div class="alert alert-info">
                        <p>
                            <strong>Обратите внимание!</strong> Для отправки уведомлений и новостей, вам необходимо
                            <a target="_blank" href="@Url.Action("ConfirmEmail", new { email = email.Value, index = email.NameField.Replace("EmailValue", "") })">
                                подтвердить адрес электронной почты @email.Value</a>.</p>
                    </div>
                }
                @if ((bool)ViewData["changessaved"])
                {
                    <div class="alert alert-success">
                        <button class="close" data-dismiss="alert">
                            ×</button><p>
                                <strong>Поздравляем!</strong> Изменения успешно сохранены.</p>
                    </div>
                }
                @using (Html.BeginForm("Index", "Account", FormMethod.Post, new { @class = "form-horizontal", id = "form1" }))
                {
                    <fieldset>
                        <div class="control-group">
                            <label class="control-label" for="uid">
                                Идентификатор</label>
                            <div class="controls">
                                <p class="form-text">
                                    @Model.CurrentUser.Id
                                </p>
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label" for="name">
                                Имя</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.FirstName, new { @class = "input-large", id = "name", autocomplete = "off" })
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label" for="surname">
                                Фамилия</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.LastName, new { @class = "input-large", id = "surname", autocomplete = "off" })
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.MiddleName) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="patronymic">
                                Отчество</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.MiddleName, new { @class = "input-large", id = "patronymic", autocomplete = "off" })
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label" for="sex">
                                Пол</label>
                            <div class="controls">
                                <label class="radio inline">
                                    @Html.RadioButtonFor(x => x.Sex, "Мужчина")
                                    Мужчина
                                </label>
                                <label class="radio inline">
                                    @Html.RadioButtonFor(x => x.Sex, "Женщина")
                                    Женщина
                                </label>
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.Company) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="company">
                                Компания</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.Company, new { @class = "input-large", id = "company" })
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.Post) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="post">
                                Должность</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.Post, new { @class = "input-large", id = "post" })
                            </div>
                        </div>
                        <div class="@(string.IsNullOrEmpty(Model.Department) ? "control-group hide" : "control-group")">
                            <label class="control-label" for="department">
                                Отдел</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.Department, new { @class = "input-large", id = "department" })
                            </div>
                        </div>
                        <hr>
                        <div class="control-group">
                            <label class="control-label" for="birthday">
                                Дата рождения</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.BirthDay, new { @class = "input-small date", id = "birthday" })
                            </div>
                        </div>
                        <hr>
                        @foreach (var phone in Model.ListPhones)
                        {
                            <div class="control-group">
                                <label class="control-label" for="@phone.NameField">
                                    Телефон</label>
                                <div class="controls">
                                    @Html.TextBox(phone.NameField, phone.Value, new { @class = "input-large phone", type = "tel", id = phone.NameField })
                                    @Html.DropDownList("PhoneType", phone.ItemList, new { @class = "input-medium" })
                                    <p class="help-block">
                                        Реальный номер <a href="#">видите только вы.</a></p>
                                </div>
                            </div>
                        }
                        @foreach (var email in Model.ListEmails)
                        {
                            <div class="control-group">
                                <label class="control-label" for="@email.NameField">
                                    Электронная почта</label>
                                <div class="controls">
                                    @Html.TextBox(email.NameField, email.Value, new { @class = "input-large", type = "email", id = email.NameField })
                                    @Html.DropDownList("EmailType", email.ItemList, new { @class = "input-medium" })
                                </div>
                            </div>
                        }
                        @foreach (var im in Model.ListIm)
                        {
                            <div class="control-group">
                                <label class="control-label" for="@im.NameField">
                                    IM</label>
                                <div class="controls">
                                    @Html.TextBox(im.NameField, im.Value, new { @class = "input-large", id = im.NameField })
                                    @Html.DropDownList("ImType", im.ItemList, new { @class = "input-medium" })
                                </div>
                            </div>
                        }
                        @foreach (var socnet in Model.ListSocNetworks)
                        {
                            <div class="@(string.IsNullOrEmpty(socnet.Value) ? "control-group hide" : "control-group")">
                                <label class="control-label" for="@socnet.NameField">
                                    Соцсеть</label>
                                <div class="controls">
                                    @Html.TextBox(socnet.NameField, socnet.Value, new { @class = "input-large", id = socnet.NameField })
                                    @Html.DropDownList("SocNetType", socnet.ItemList, new { @class = "input-medium" })
                                </div>
                            </div>
                        }
                        <hr>
                        <div class="control-group">
                            <label class="control-label" for="region">
                                Регион</label>
                            <div class="controls">
                                @Html.DropDownListFor(x => x.Region, Model.ListForRegion, new { @class = "input-large", id = "region" })
                            </div>
                        </div>
                        @Html.Hidden("countaddress", 0)
                        @foreach (var address in Model.ListAddresses)
                        {
                            <div class="control-group">
                                <label class="control-label" for="@address.NameField">
                                    Адрес</label>
                                <div class="controls">
                                    @Html.TextArea(address.NameField, address.Value, new { @class = "input-large", placeholder = "Город, улица, дом ", rows = "3", id = address.NameField, typefield = "address" })
                                </div>
                            </div>
                        }
                        <div class="@(Model.DateLawToCar == DateTime.MinValue.ToString("dd.MM.yyyy") ? "control-group hide" : "control-group")">
                            <label class="control-label" for="DateLawToCar">
                                Дата получения прав</label>
                            <div class="controls">
                                @Html.TextBoxFor(x => x.DateLawToCar, new { @class = "input-small date", id = "DateLawToCar" })
                                <span id="experience" class="help-inline"></span>
                            </div>
                        </div>
                        <hr>
                        <div class="control-group">
                            <label class="control-label" for="password">
                                Сменить пароль</label>
                            <div class="controls">
                                <div class="input-append">
                                    <nobr>
                                    @Html.PasswordFor(x => x.TopPassword, new { @class = "input-large", id = "password", placeholder = "Старый пароль", autocomplete = "off" })@Html.TextBoxFor(m => m.TopPassword, new { id = "top-password-text", @class = "input-large", type = "text", style = "display:none", placeholder = "Старый пароль", onblur = "SetPassword('#password', '#top-password-text');" })<button onclick="ShowPassword('#password', '#top-password-text');" class="btn" type="button" title="Отобразить пароль">
                                        <i class="icon-eye-close"></i>
                                    </button>
                                </nobr>
                                </div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <div class="input-append">
                                    <nobr>
                                @Html.PasswordFor(x => x.NewPassword, new { id = "newpassword", @class = "input-large", placeholder = "Новый пароль", autocomplete = "off" })@Html.TextBoxFor(m => m.NewPassword, new { id = "password-text", @class = "input-large", type = "text", style = "display:none", placeholder = "Новый пароль", onblur = "SetPassword('#newpassword', '#password-text');" })<button onclick="ShowPassword('#newpassword', '#password-text');" class="btn" type="button" title="Отобразить пароль">                                    
                                <i class="icon-eye-close"></i>
                                </button>
                                </nobr>
                                </div>
                            </div>
                        </div>
                        <div class="control-group">
                            <div class="controls">
                                <div id="addField" class="btn-group dropup">
                                    <button class="btn dropdown-toggle" data-toggle="dropdown">
                                        Добавить поле <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        @if (string.IsNullOrEmpty(Model.MiddleName))
                                        {
                                            <li><a href="javascript:void(0)">Отчество</a></li>
                                            <li class="divider"></li>
                                        }
                                        @if (string.IsNullOrEmpty(Model.Company))
                                        {
                                            <li><a href="javascript:void(0)">Компания</a></li>
                                        }
                                        @if (string.IsNullOrEmpty(Model.Post))
                                        {
                                            <li><a href="javascript:void(0)">Должность</a></li>
                                        }
                                        @if (string.IsNullOrEmpty(Model.Department))
                                        {

                                            <li><a href="javascript:void(0)">Отдел</a></li>
                                        }
                                        @if (string.IsNullOrEmpty(Model.Department) || string.IsNullOrEmpty(Model.Post) || string.IsNullOrEmpty(Model.Company))
                                        {
                                            <li class="divider"></li>
                                        }
                                        <li><a href="javascript:void(0)">Телефон</a></li>
                                        <li><a href="javascript:void(0)">Электронная почта</a></li>
                                        <li><a href="javascript:void(0)">IM</a></li>
                                        <li><a href="javascript:void(0)">Соцсеть</a></li>
                                        <li><a href="javascript:void(0)">Адрес</a></li>
                                        @if (Model.DateLawToCar == DateTime.MinValue.ToString("dd.MM.yyyy"))
                                        {
                                            <li class="divider"></li>
                                            <li><a href="javascript:void(0)">Дата получения прав</a></li>
                                        }
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button class="btn btn-primary btn-large" onclick="PostData();">
                                Сохранить и продолжить</button>
                        </div>
                    </fieldset>
                }
            </div>
            <div class="span4">
                <div class="control-group">
                    <div class="controls">
                        <div class="thumbnail">
                            <img id="avatar" src="@(Model.CurrentUser.Avatar!="0" ? Url.Image(Model.CurrentUser.Avatar, 250, 290) : Url.VirtualImageUrl("avatar.gif"))" alt="">
                            <div class="caption">
                                <div class="btn-group">
                                    <input type="file" class="btn" name="avatar_upload" id="avatar_upload" style="display: inline-block;" />
                                    <button class="btn" rel="tooltip" title="Удалить фотографию" onclick="DeleteAvatar();">
                                        <i class="icon-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
